jquery.form 和MVC4做无刷新上传DEMO
HTML:
JS:
$(document).ready(function(){ $('input.tino_file').each(function(){ var form=$(this).parents("form"); form.attr('enctype','multipart/form-data'); var old_name=$(this).attr('name'); $(this).hide(); var new_name=old_name+'_file'; var imgstyle=$(this).attr('imgstyle'); var imgstr=''; var old_file=$(this).val(); if(''!=old_file) { imgstr=' 删除'; } var str=''+imgstr+''; $(this).after(str); var ahah=$(this); $('#'+new_name).change(function(){ var tmp=$(this).val(); if(''!=tmp) { //alert(ahah.val()); form.ajaxSubmit({ url:"/Home/UploadImage", type: 'POST', data:{ 'field':new_name,'only_img':'yes','old_img':$('#'+new_name+'_del').val()}, dataType: "json", //beforeSend:function(){loading_start();}, success: function(result) { if ('' != result.url) { var tmp = result; $('#' + new_name + '_show').html(' 删除'); ahah.val(tmp.url); $('#' + new_name + '_del').val(tmp.realpath); window.onbeforeunload = function () { } } else { alert("请选择正确图片上传"); } } }); } }); });
Contoller:
public JsonResult UploadImage() { var relativeurl = "";//相对路径 var realurlpath = "";//绝对路径 if (Request.Files.Count <= 0) return Json(new { url =relativeurl, realpath=realurlpath }); for(var i = 0;i < Request.Files.Count;i++) { var extensionname = DateTime.Now.ToString("yyyyMMddmmss"); var file = HttpContext.Request.Files[i]; if (file == null || file.ContentLength <= 0) continue; var originExtensionName = EnHtml(HttpUtility.UrlDecode(file.FileName,Encoding.GetEncoding("GB2312"))).Substring(EnHtml(HttpUtility.UrlDecode(file.FileName,Encoding.GetEncoding("GB2312"))).Length - 3); if (originExtensionName.ToLower() != "jpg" && originExtensionName.ToLower() != "gif") continue; var newFile = extensionname + "." + originExtensionName; relativeurl = newFile; realurlpath = "/upfile/" + newFile; file.SaveAs(HttpContext.Server.MapPath("/upfile/" + newFile)); } return Json(new { url = relativeurl, realpath = realurlpath }); } private static string EnHtml(string str) { if(str == null) return ""; str = str.Replace(" ",""); str = str.Trim(); return str; }